﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Manager;
using Model;
using ExtAspNet;
using System.IO;
namespace HealthSystem
{
    public partial class School :BasePage
    {
        HW_SchoolManager manager = new HW_SchoolManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            Initialize();
            if (!IsPostBack)
            {
                //Newbt.OnClientClick = Window2.GetShowReference("School_New.aspx");
                name.OnClientTriggerClick = Window1.GetSaveStateReference(districtid.ClientID,name.ClientID)
                   + Window1.GetShowReference("./ChooseDistrict.aspx","地区选择");
                BindGrid();
                if (CustomerProfile.RoleId == 1003 || CustomerProfile.RoleId == 1012)
                {
                    districtid.Text = CustomerProfile.AdminUser.DistrictCode;
                    name.Text = CustomerProfile.AdminUser.hW_District.Name;
                    name.Readonly = true;
                }
            }
        }
        public void BindGrid()
        {
            int count = 0;
            DataTable list = null;
            //DataTable list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, district);
            if (CustomerProfile.RoleId.ToString().StartsWith("1"))
            {
                if (actionbt.Text == "search")
                {
                    if (!string.IsNullOrEmpty(districtid.Text))
                    {
                        list = manager.Search(Gird1.PageIndex, Gird1.PageSize, out count, districtid.Text.Trim(), searchbox.Text);
                    }
                    else
                    {
                        list = manager.Search(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId, searchbox.Text);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(districtid.Text))
                    {
                        list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, districtid.Text.Trim());
                        //BindGrid(districtid.Text.Trim());
                    }
                    else
                    {
                        list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId);
                        //BindGrid(CustomerProfile.DistrictId);
                    }
                }
            }
            if (CustomerProfile.RoleId == 2000)
            {
                list = manager.GetSchoolByOrgCode(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.OrgUser.OrgCode);
            }
            if (CustomerProfile.RoleId == 3000)
            {
                list = manager.GetSchoolBySchoolCode(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.SchoolUser.SchoollCode);
            }
            Gird1.RecordCount = count;
            this.Gird1.DataSource = list;
            this.Gird1.DataBind();
        }
        public void Grid1_DoubleClick(object sender,ExtAspNet.GridRowClickEventArgs e)
        {
            string schoolcode= Gird1.Rows[e.RowIndex].DataKeys[0] as string;
            string schoolname = Gird1.Rows[e.RowIndex].DataKeys[1] as string;
            string url="schoolsignadmin.aspx?schoolcode="+schoolcode;
            PageContext.RegisterStartupScript(Window2.GetShowReference(url, schoolname+"用户"));
        }
        public void Window1_Close(object sender,EventArgs e)
        {
            if (!string.IsNullOrEmpty(districtid.Text))
            {
                Gird1.PageIndex = 0;
                BindGrid();
                actionbt.Text = "";
            }
        }
        protected void PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            int pageindex = e.NewPageIndex;
            Gird1.PageIndex = pageindex;
            BindGrid();
        }
        protected void Search_Clik(object sender, EventArgs e)
        {
            actionbt.Text = "search";
            Gird1.PageIndex = 0;
            Search();
            
        }
        private void Search()
        {
            if (string.IsNullOrEmpty(searchbox.Text))
            {
                ExtAspNet.Alert.Show("请输入查询条件");
                return;
            }
            BindGrid();
        }
        protected void Grid1_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            try
            {
                string username = Gird1.Rows[e.RowIndex].DataKeys[0].ToString();
                //if (e.CommandName == "delete")
                //{
                //    manager.DeleteById(username);
                //    BindGrid();

                //}
                if (e.CommandName == "reset")
                {
                    //重置密码
                    HW_School_UserManager schoolUserManager = new HW_School_UserManager();
                    string pass = System.Configuration.ConfigurationManager.AppSettings["default"].ToString();
                    int n=schoolUserManager.ResetPassWord(username, pass);
                    if(n==1)
                    Alert.Show("密码重置成功");
                    else
                        Alert.Show("密码出错!");
                    //BindGrid();
                }
                if (e.CommandName == "download")
                {
                    string p = Gird1.Rows[e.RowIndex].DataKeys[2].ToString().ToLower();
                    if (p != "true")
                    {
                        Alert.Show("该学校未授权!");
                        return;
                    }
                    //string path = System.Configuration.ConfigurationManager.AppSettings["SignDir"].ToString();
                    //string name = Gird1.Rows[e.RowIndex].DataKeys[1].ToString();
                    string id=Gird1.Rows[e.RowIndex].DataKeys[0].ToString();
                    //string filename = path + "\\" + id + ".gdsx";
                    //if (!System.IO.File.Exists(filename))
                    //{
                    //    Alert.Show("文件不存在");
                    //    return;
                    //}
                    Window1.Width = 100;
                    Window1.Height = 50;
                    PageContext.RegisterStartupScript(Window3.GetShowReference("test.aspx?id=" + id, "验证文件下载"));
                }
            }
            catch(Exception ex)
            {
                Alert.Show("操作失败!");
            }
        }
        public void Initialize()
        {
            if (!CustomerProfile.RoleId.ToString().StartsWith("1"))
            {
                lable1.Visible = false;
                name.Visible = false;
                searchbox.Visible = false;
            }
            if (CustomerProfile.RoleId == 2000 || CustomerProfile.RoleId==1001)
            {
                ExtAspNet.LinkButtonField link = new LinkButtonField();
                link.HeaderText = "验证文件下载";
                link.Text = "验证文件下载";
                link.CommandName = "download";
                Gird1.Columns.Add(link);
            }
        }
        #region 下载文件
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="WebForm"></param>
        /// <param name="FileNameWhenUserDownload"></param>
        /// <param name="FilePath"></param>
        public void DownloadFile(string fileName, string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                fileName=HttpContext.Current.Server.UrlEncode(fileName); 
                FileInfo fileInfo = new FileInfo(filePath);
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                Response.WriteFile(fileInfo.FullName);
                Response.Flush();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }





//            System.IO.FileInfo info = new System.IO.FileInfo(filePath); 
//            long fileSize = info.Length; 
//            Response.Clear(); 
//            Response.ContentType = "application/x-zip-compressed"; 
//            Response.AddHeader("Content-Disposition", "attachment;filename="+ fileName); 
////不指明Content-Length用Flush的话不会显示下载进度 
//            Response.AddHeader("Content-Length", fileSize.ToString()); 
//            Response.TransmitFile(filePath, 0, fileSize); 
//            Response.Flush(); 
//            Response.Close(); 
        }
        #endregion
    }
}